import React from 'react'
import { Modal, info, Select, success, FileUpload, Button,Link, TitleBar } from '../../ui-components'
import { connect } from 'react-redux'
import style from './style.upload-profile'
import { getToken } from '../../actions/util'
/*import store from 'yields-store'*/
import Upload from 'component-upload'
import util from '../../util'
import { help as styleHelp } from '../onboarding/staff/style.fill' 
import cookie from 'component-cookie';

export default
@connect(({ onboardingFlowsHr, profileTemplate }) => ({ profileTemplate, onboardingFlowsHr }))
class UploadProfile extends React.Component {

  init = {
    loadingTempates: true,
    //profileTemplateId: '',
    step: 1,
    file: null,
    upload: null,
    error: '',
    number: '',
    dataError: false,
    dataErrorHandle: false,
    dataErrorHandleDone: false,
    requestHandleCSV: false,
  }

  state = {
    ...this.init
  }

  getUrl = (name) => `/onboarding-flows/profile-templates-csv-files/${name}` 

  handleCSV() {
    this.props.manualHandleCSV(this.CSVDocument, () => {
      this.setState({
        dataErrorHandleDone: true
      })
    })
    this.setState({
      requestHandleCSV: false
    })
  }

  upload() {
    const upload = new Upload(this.state.file)
    info('上传中...', true)
    upload.to({
      headers: {
        'X-Access-Token': cookie('X-Access-Token'), 
        'X-Refresh-Token': cookie('X-Refresh-Token'),
      },
      path: this.getUrl('upload')
    })
    upload.on('progress', () => {})
    upload.on('end', res => {
      res = JSON.parse(res.responseText)
      if (/^2\d+$/.exec(res.code)) {
        success('上传成功!')
        this.setState({
          upload: true,
          number: res.data.totalCount
        })
      } 
      // 数据格式有误
      else if ('4000309' == res.code) {
        info()
        this.setState({
          upload: false,
          dataError: true
        })
        this.props.createDocument({ scenario: 3, documentName: this.state.file.name, storageStatus: 1 }, data => {
          const { documentId, presignedUrl } = data
          this.CSVDocument = documentId
          this.props.fileUpload({
            file: this.state.file,
            url: presignedUrl,
            cb: () => {
              this.setState({
                dataErrorHandle: true
              })
            }
          })
        })
      }
      else {
        info()
        this.setState({
          upload: false,
          error: res.errorInfo || res.msg
        })
      }
    })
  }

  handleUpload(file) {
    this.setState({
      file: file.file
    })
  }

  componentDidMount() {
    this.props.fetchOnboardingUnhandleTasks()
  }

  componentWillUnmount() {
    this.props.resetOnboardingFlows()
  }

  render() {
    const { list } = this.props.profileTemplate
    const { loadingTempates } = this.state
    const { tasks } = this.props.onboardingFlowsHr

    let actions
    if (this.state.upload !== null) {
      actions = () => (
        <div className={style.actions}>
          {
            this.state.dataError? (
              !this.state.dataErrorHandleDone? (
                <Button 
                  disabled={!this.state.dataErrorHandle} 
                  label="授权人工处理" 
                  onClick={() => {
                    console.log('ddd')
                    this.setState({ requestHandleCSV: true })
                  }}
                />
              ): null
            ): (
              <Button label="完成" onClick={() => {
                this.setState({
                  upload: null,
                  error: '',
                  file: null,
                  number: ''
                })
              }}/>
            )
          }
        <Button blueLine={!this.state.dataErrorHandleDone} label={this.state.upload? "继续上传": "重新上传"} onClick={() => {
          this.setState({
            upload: null,
            error: '',
            file: null,
            number: '',
            dataErrorHandle: false,
            dataError: false,
            dataErrorHandleDone: false
          })
        }}/>
        </div>
      ) 
    }

    const titleBar = (
      <div>
        <TitleBar back label="邀请员工"/>
      </div>
    );

    if (this.state.upload) {
      return (
        <div>
          { titleBar }
          <div className={style.body}>
            <div>
              <div className={style['upload-success']}>上传成功，已成功导入{ this.state.number }名员工的档案</div>
              { actions? actions(): null }
            </div>
          </div>
        </div>
      )
    }

    // 数据格式有误
    if (this.state.dataError) {
      return (
        <div>
          { titleBar }
          <div className={style.body}>
            <div>
              <div className={style['upload-error']}>{ this.state.dataErrorHandleDone? '您已授权人工处理，请注意查收邮件，感谢您的耐心等待。': '因格式无法解析，数据上传失败，建议授权人工处理。'}</div>
              { actions? actions(): null }
            </div>
          </div>
          <Modal
            active={this.state.requestHandleCSV}
            onRequestClose={() => this.setState({ requestHandleCSV: false })}
            actions={[
              'cancel',
              ::this.handleCSV
            ]}
            title="授权人工处理"
          >
            <div>确认授权人工处理？格式校正后的 CSV 将发送到您的邮箱，您收到后可以重新上传。在此期间内请勿修改员工档案模板。</div>
          </Modal>
        </div>
      )
    }

    // 失败
    if (this.state.upload === false) {
      return (
        <div>
          { titleBar }
          <div className={style.body}>
            <div>
              <div className={style['upload-error']}>上传或导入失败，此次导入员工档案 0 个。请阅读提示，解决问题后重新上传。</div>
              <textarea disabled className={style['error-info']} defaultValue={ this.state.error}/>
              { actions? actions(): null }
            </div>
          </div>
        </div>
      )
    }



    return (
      <div>
        { titleBar }
        <div className={style.body}>
          
          {
            
              <form action={this.getUrl('download')} method="post">
                <input type="hidden" name="X-Access-Token" value={cookie('X-Access-Token')}/>
                <input type="hidden" name="X-Refresh-Token" value={cookie('X-Refresh-Token')}/>
                <div className={style['handle-template']}>
                  <Button label="点击下载表格模板（CSV）" className={style.download}/>
                  <div>
                    <label>选择员工档案表（CSV）：</label>
                    <div style={{width: '100px', marginTop: '10px'}}>
                      <FileUpload
                        className={style['pick-file']}
                        link
                        placeholder="选取文件"
                        onChange={::this.handleUpload}
                      />
                    </div>
                    <span>{ !this.state.file? '（未选择文件）': this.state.file.name }</span>
                  </div>
                </div>
              </form>
          }

          {
            this.state.file? (
              <Button 
                onClick={::this.upload} 
                className={style['upload-button']} 
                label="上传并导入数据" 
                disabled={!this.state.file}
              />
            ): null
          }
        </div>
      </div>
    )
  }
}
